import type { ComponentStyleIdType, PlatformTypeValue } from '../../../types/interfaces'
import { BaseModule } from '../../../lib/abstract'
import {
  ComponentStyleId,
  HOSTNAME,
  logger,
  SUPPORTED_PLATFORMS,
} from '../../../types/constants'
import { ConfigManager } from '../../config_manager'

interface Config {
  enabled?: boolean
}

export class StealthSearch extends BaseModule {
  readonly id: string = 'stealth_search'
  readonly styleId: string = ComponentStyleId[this.name]
  isInitialized: boolean = false
  readonly supportedPlatforms: string[] = ConfigManager.getInstance().moduleSupportedPlatforms(this.name)
  private static instance: StealthSearch

  config: Config = {
    enabled: true,
  }

  get name(): ComponentStyleIdType {
    return 'StealthSearch'
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): StealthSearch {
    if (!StealthSearch.instance) {
      StealthSearch.instance = new StealthSearch()
    }
    return StealthSearch.instance
  }

  handleCleanupOthers(): void {
    this.toggleSearchAutocomplete(true)
  }

  core(): void {
    this.loadConfig()

    if (!this.config.enabled)
      return

    this.toggleSearchAutocomplete(false)
  }

  onToggleCallback(_id: string, checked: boolean): void {
    super.onToggleCallback(_id, checked)
  }

  toggleSearchAutocomplete(enabled: boolean): void {
    const config: Partial<Record<PlatformTypeValue, { selector: string }>> = {
      [SUPPORTED_PLATFORMS.GREASY_FORK]: {
        selector: 'input[type="search"]',
      },
      [SUPPORTED_PLATFORMS.BAI_DU]: {
        selector: 'body > form table input',
      },
    }

    const platformConfig = config[HOSTNAME]

    if (!platformConfig)
      return

    $(platformConfig.selector).attr('autocomplete', enabled ? 'on' : 'off')
  }

  applyConfig(config: Partial<Config>): void {
    super.updateConfig(config)

    this.toggleSearchAutocomplete(false)

    logger.info(`[${this.name}] Config updated and apply`, this.config)
  }

  getStyles(): string {
    return `
`
  }
}
